package cn.uin.domain.auth.service.user.login.handle;

import cn.uin.domain.auth.adapter.repository.IAuthRepository;
import cn.uin.domain.auth.model.entity.HomeRoleEntity;
import cn.uin.types.enums.ResponseCode;
import cn.uin.types.exception.AppException;
import cn.uin.types.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @ClassName CustomAuthorizationFilter
 * @Description:处理HTTP请求的BASIC授权
 * @Author: Administrator
 * @CreateDate: 2025/10/24 16:38
 * @Version: 1.0
 */
public class CustomAuthorizationFilter extends BasicAuthenticationFilter {

	private static final String TOKEN_HEADER = "Authorization";

	private static final String TOKEN_PREFIX = "Bearer ";

	@Autowired
	private IAuthRepository iAuthRepository;

	public CustomAuthorizationFilter(AuthenticationManager authenticationManager) {
		super(authenticationManager);
	}

	@Override
	protected void doFilterInternal(HttpServletRequest request,
	                                HttpServletResponse response,
	                                FilterChain chain) throws IOException, ServletException {
		String tokenHeader = request.getHeader(TOKEN_HEADER);
		// 如果请求头中没有Authorization信息则直接放行了
		if (tokenHeader == null || !tokenHeader.startsWith(TOKEN_PREFIX)) {
			chain.doFilter(request, response);
			return;
		}
		// 如果请求头中有token，则进行解析，并且设置认证信息
		SecurityContextHolder.getContext().setAuthentication(getAuthentication(tokenHeader));
		super.doFilterInternal(request, response, chain);
	}

	/**
	 * 这里从token中获取用户信息并新建一个token
	 * @param tokenHeader
	 * @return
	 */
	private UsernamePasswordAuthenticationToken getAuthentication(String tokenHeader) {
		String token = tokenHeader.replace(TOKEN_PREFIX, "");
		String username = JwtUtils.getUsername(token);
		boolean tokenFlag = iAuthRepository.checkToken(username, token);
		if (!tokenFlag) {
			throw new AppException(ResponseCode.A0004.getCode(), ResponseCode.A0004.getInfo());
		}
		List<String> userMenus = JwtUtils.getUserMenus(token);
		List<SimpleGrantedAuthority> authorities = new ArrayList<>();
		if (!CollectionUtils.isEmpty(userMenus)) {
			for (String authority : userMenus) {
				SimpleGrantedAuthority auth = new SimpleGrantedAuthority(authority);
				authorities.add(auth);
			}
		}
		if (username != null) {
			return new UsernamePasswordAuthenticationToken(username, null, authorities);
		}
		return null;
	}
}
